package com.example.course.controller;

import com.example.course.bean.Register;
import com.example.course.bean.Student;
import com.example.course.bean.Teacher;
import com.example.course.mapper.RegisterMapper;
import com.example.course.service.StudentService;
import com.example.course.service.TeacherService;
import com.example.course.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class RegisterController {
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private StudentService studentService;
    @Resource
    private TeacherService teacherService;

    @RequestMapping("/course/register")
    public String register(Register register) {
        int i = registerMapper.insertRegister(register);
        if(i == 0){
            return "register";
        }else {
            return "login";
        }
    }
    @RequestMapping("/course/showRegister")
    @ResponseBody
    public Result showRegister() {
        List<Register> registerList = registerMapper.selectRegisters();
        return new Result(registerList);

    }
    @RequestMapping("/course/agreeRegister/{id}")
    @ResponseBody
    public Result agreeRegister(@PathVariable int id) {
        Register register = registerMapper.selectRegister(id);
        if (register.getType().equals("teacher")) {
            int i = teacherService.insertTeacher(new Teacher(register.getAccount(), register.getPassword()));
            int i1 = registerMapper.deleteRegister(register.getId());
            if (i >0 ) {
                if (i1 == 0) {
                    return new Result("该数据重复，自动删除");
                } else {
                    return Result.success();
                }
            }
        } else if (register.getType().equals("student")) {
            int i = studentService.insertStudent(new Student(register.getAccount(), register.getPassword()));
            int i1 = registerMapper.deleteRegister(register.getId());
            if (i == 1) {
                if (i1 == 0) {
                    return new Result("该数据重复，自动删除");
                } else {
                    return Result.success();
                }
            }
        }
        return Result.fail();
    }
    @RequestMapping("/course/notAgreeRegister/{id}")
    @ResponseBody
    public Result deleteRegister(@PathVariable int id) {
        int i = registerMapper.deleteRegister(id);
        if (i == 0) {
            return Result.fail();
        } else {
            return Result.success();
        }
    }
}
